package com.xbrother.lucene.store;

import org.apache.lucene.store.IndexOutput;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;

/**
 * IndexInput 和 IndexOutput 是用于读取和写入索引数据的类，需要将它们与数据库操作绑定。
 *
 * @author huangchangjin
 * @date 2025/5/13 19:32
 */
public class DatabaseIndexOutput extends IndexOutput {

    private final DatabaseIndexStore databaseIndexStore;
    private final String fileName;
    private final ByteArrayOutputStream buffer;
    private final CRC32 crc = new CRC32();

    public DatabaseIndexOutput(String fileName, DatabaseIndexStore databaseIndexStore) {
        super("DatabaseIndexOutput(file=" + fileName + ")", fileName);
        this.fileName = fileName;
        this.databaseIndexStore = databaseIndexStore;
        this.buffer = new ByteArrayOutputStream();
    }

    @Override
    public void writeByte(byte b) {
        buffer.write(b);
        crc.update(b);
    }

    @Override
    public void writeBytes(byte[] b, int offset, int length) {
        buffer.write(b, offset, length);
        crc.update(b, offset, length);
    }

    @Override
    public void close() throws IOException {
        try {
            byte[] data = buffer.toByteArray();
            databaseIndexStore.writeFile(fileName, data);
        } finally {
            buffer.reset(); // 清空缓冲区以便复用
        }
    }

    @Override
    public long getFilePointer() {
        return buffer.size();
    }

    @Override
    public long getChecksum() {
        return crc.getValue();
    }
}
